package com.demo.impl.service;

import com.demo.api.user.domain.TestLimit;
import com.demo.api.user.domain.TestUser;
import com.demo.api.user.service.LimitService;
import com.demo.api.user.service.UserService;
import com.demo.common.enums.ResultCode;
import com.demo.common.response.Result;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

/**
 *
 * @author
 * @since
 */
@Component
@Slf4j
public class OpenNewUserServiceImpl implements OpenNewUserService {

  @Reference(version = "1.0.0", check = false)
  private LimitService limitService;

  @Reference(version = "1.0.0", check = false)
  private UserService userService;

  @SneakyThrows
  @Override
  @GlobalTransactional
  public void addLimitRollback() {
    log.info("分布式事务, xid:{}", RootContext.getXID());
    TestLimit testLimit = new TestLimit();
    testLimit.setIdno("999");
    testLimit.setLimitAmount(new BigDecimal(111));
    testLimit.setDt(new Date());
    Result<Boolean> result = limitService.addLimit(testLimit);
    log.info("dubbo 处理结果：{}", result);
    throw new Exception("测试异常");
  }

  @SneakyThrows
  @Override
  @GlobalTransactional
  public void addUserAndLimit() {
    log.info("分布式事务, xid:{}", RootContext.getXID());
    log.info("新增用户信息");
    // add user
    TestUser testUser = new TestUser();
    testUser.setFullName("");
    testUser.setIdno("2");
    testUser.setSex("3");
    Result result = userService.addUser(testUser);
    log.info("{}", result);
    if (!ResultCode.SUCCESS.code().equals(result.getStatus())) {
      throw new Exception("创建用户失败");
    }

    log.info("新增用户信息成功，现在新增额度信息");
    TestLimit testLimit = new TestLimit();
    testLimit.setIdno("777");
    testLimit.setLimitAmount(new BigDecimal(933));
    testLimit.setDt(new Date());
    result = limitService.addLimit(testLimit);
    log.info("{}", result);
    if (!ResultCode.SUCCESS.code().equals(result.getStatus())) {
      throw new Exception("创建额度失败");
    }
    log.info("新增额度信息成功，流程结束");
  }

  @Override
  @GlobalTransactional
  public void addLimitCommit() {
    log.info("分布式事务, xid:{}", RootContext.getXID());
    TestLimit testLimit = new TestLimit();
    testLimit.setIdno("888");
    testLimit.setLimitAmount(new BigDecimal(222));
    testLimit.setDt(new Date());
    Result result = limitService.addLimit(testLimit);
    log.info("dubbo 处理结果：{}", result);
  }
}
